package com.qipa.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 服务的主入口，这个例子是发送http-json
 *
 * @author superzhan
 */

@Component
@Slf4j
public final class NettyMainConfig {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8443" : "6789"));


    @Autowired
    ServerInitializer serverInitializer;

    public void start() throws Exception {


        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);//一个老板够了
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();   // netty服务器的创建, 辅助工具类，用于服务器通道的一系列配置
            b.option(ChannelOption.SO_BACKLOG, 1024);//服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)// 设置并绑定服务端Channel,指定所使用的NIO传输的Channel
                    .handler(new LoggingHandler(LogLevel.ERROR))//日志打印
                    .childHandler(serverInitializer);//设置子通道也就是SocketChannel的处理器， 其内部是实际业务开发的"主战场"

            //绑定并侦听某个端口
            Channel ch = b.bind(PORT).sync().channel();

            log.info("服务启动成功。Open your web browser and navigate to " +
                    (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/');

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
